Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head){
}
本題是linked list的第3題,題目是輸入1個linked list,要回傳這個linked list最中央的節點,如果中央節點有2個,則回傳第二個,如下圖Fig. 1所示,當節點數量是奇數時回傳最中間的節點,當節點數量是偶數時回傳右邊那個節點。
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* ptr_array[100] = {NULL};
struct ListNode* ptr;
int index = 0;
ptr = head;
while (ptr != NULL) {
ptr_array[index] = ptr;
index++;
ptr = ptr->next;
}
return ptr_array[index / 2];
}
今天發文滿一週了,謝謝大家!